<template>
  <div class="dashboard-container">
    <!-- 1. 顶部功能区 -->
    <div class="top-nav">
      <div class="nav-buttons">
        <el-tooltip
          v-for="btn in actions"
          :key="btn.name"
          :content="btn.tip"
          placement="bottom"
        >
          <el-button
            :type="btn.requiredAdmin && !isAdmin ? 'text' : 'primary'"
            :disabled="btn.requiredAdmin && !isAdmin"
            @click="handleAction(btn)"
            class="nav-btn"
          >
            <i :class="btn.icon"></i>
            {{ btn.name }}
          </el-button>
        </el-tooltip>
      </div>
      <div class="user-info">
        <span class="welcome">欢迎您，{{ userName }}</span>
        <el-tag :type="userRole === 'admin' ? 'success' : ''">{{ roleNames[userRole] }}</el-tag>
        <el-button type="text" @click="logout" icon="el-icon-switch-button"></el-button>
      </div>
    </div>

    <!-- 2. 主体内容区 -->
    <div class="main-content">
      <!-- 左半屏 - 统计分析区 -->
      <div class="left-panel">
        <!-- 实时用电监控 -->
        <el-card shadow="hover" class="chart-card">
          <div class="chart-header">
            <h3><i class="el-icon-data-line"></i> 实时用电监控</h3>
            <el-select
              v-model="timeRange"
              @change="updateChart"
              size="mini"
              style="width: 120px"
            >
              <el-option label="今日" value="day"></el-option>
              <el-option label="本周" value="week"></el-option>
              <el-option label="本月" value="month"></el-option>
            </el-select>
          </div>
          <div id="realTimeChart" class="chart-container"></div>
        </el-card>

        <!-- 区域用电分布 -->
        <el-card shadow="hover" class="chart-card">
          <h3><i class="el-icon-pie-chart"></i> 区域用电分布</h3>
          <div id="regionPie" class="chart-container"></div>
        </el-card>
      </div>

      <!-- 右半屏 -->
      <div class="right-panel">
        <!-- 3. 报警分析区 -->
        <el-card shadow="hover" class="alert-card">
          <el-tabs v-model="activeAlertTab">
            <el-tab-pane label="异常设备" name="abnormal">
              <div class="alert-header">
                <h4><i class="el-icon-warning"></i> 异常设备监控</h4>
                <span class="badge">{{ abnormalDevices.length }}</span>
              </div>
              <div class="device-list">
                <div
                  v-for="(device, index) in abnormalDevices"
                  :key="index"
                  class="device-item"
                  :class="{warn: device.power > 1500}"
                >
                  <div class="device-info">
                    <span class="location">{{ device.location }}</span>
                    <span class="name">{{ device.name }}</span>
                    <el-tag size="mini" type="danger">{{ device.power }}W</el-tag>
                  </div>
                  <el-button
                    size="mini"
                    type="danger"
                    plain
                    @click="cutoffPower(device)"
                    v-if="isAdmin"
                  >
                    <i class="el-icon-switch-button"></i> 断电
                  </el-button>
                </div>
              </div>
            </el-tab-pane>

            <el-tab-pane label="待机设备" name="standby">
              <div class="standby-container">
                <h4><i class="el-icon-alarm-clock"></i> 待机设备监控</h4>
                <el-carousel
                  height="120px"
                  direction="vertical"
                  :autoplay="true"
                  indicator-position="none"
                >
                  <el-carousel-item v-for="(item, i) in standbyDevices" :key="i">
                    <div class="standby-item">
                      <div class="device">
                        <span class="location">{{ item.location }}</span>
                        <span class="name">{{ item.name }}</span>
                      </div>
                      <el-tag type="warning" effect="dark">待机中</el-tag>
                    </div>
                  </el-carousel-item>
                </el-carousel>
                <div class="total-consumption">
                  <span>本月待机耗电：</span>
                  <span class="value">{{ standbyPower }} kW·h</span>
                </div>
              </div>
            </el-tab-pane>
          </el-tabs>
        </el-card>

        <!-- 4. 行为分析区 -->
        <div class="behavior-container">
          <!-- 用电热力图 -->
          <el-card shadow="hover" class="heatmap-card">
            <h4><i class="el-icon-timer"></i> 24小时用电热力图</h4>
            <div id="heatmapChart" class="chart" style="height:100%;width:100%"></div>
          </el-card>

          <!-- 节能排名 -->
          <el-card shadow="hover" class="ranking-card">
            <h4><i class="el-icon-medal"></i> 节能评分排名</h4>
            <div id="rankingChart" class="chart" style="height:100%;width:100%"></div>
          </el-card>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import * as echarts from 'echarts'

export default {
  data() {
    return {
      userName: '管理员',
      userRole: 'admin',
      roleNames: {
        admin: '系统管理员',
        user: '普通用户'
      },
      timeRange: 'day',
      activeAlertTab: 'abnormal',
      actions: [
        {
          name: '充值缴费',
          icon: 'el-icon-wallet',
          tip: '账户余额充值及缴费记录查询',
          requiredAdmin: false
        },
        {
          name: '一键开户',
          icon: 'el-icon-user',
          tip: '为新用户创建水电账户',
          requiredAdmin: true
        },
        {
          name: '账单查询',
          icon: 'el-icon-document',
          tip: '查询历史水电账单',
          requiredAdmin: false
        },
        {
          name: '设备阈控',
          icon: 'el-icon-setting',
          tip: '设置设备功率阈值',
          requiredAdmin: true
        },
        {
          name: '费用报表',
          icon: 'el-icon-data-line',
          tip: '生成水电费用统计报表',
          requiredAdmin: false
        },
        {
          name: '保电设置',
          icon: 'el-icon-lock',
          tip: '紧急情况下维持供电',
          requiredAdmin: true
        }
      ],
      abnormalDevices: [
        { name: '电热水壶', power: 2000, location: '3楼A区' },
        { name: '空调', power: 1800, location: '5楼B区' },
        { name: '投影仪', power: 1600, location: '2楼会议室' }
      ],
      standbyDevices: [
        { name: '打印机', location: '5楼B区', power: 50 },
        { name: '电脑', location: '3楼办公室', power: 30 },
        { name: '饮水机', location: '1楼大厅', power: 20 }
      ],
      standbyPower: 156,
      realTimeData: [],
      regionData: [],
      heatmapData: [],
      rankingData: [],
      realTimeChart: null,
      regionPie: null,
      heatmapChart: null,
      rankingChart: null,
    }
  },
  mounted() {

    this.generateMockData()
    this.initCharts()
  },
  methods: {
    generateMockData() {
      this.realTimeData = Array.from({length: 24}, (_, i) => ({
        time: `${i}:00`,
        current: Math.floor(Math.random() * 100),
        yesterday: Math.floor(Math.random() * 100)
      }))

      this.regionData = [
        { name: '1号楼', value: 35 },
        { name: '2号楼', value: 25 },
        { name: '3号楼', value: 20 },
        { name: '4号楼', value: 15 },
        { name: '行政楼', value: 5 }
      ]

      this.heatmapData = []
      for (let i = 0; i < 7; i++) {
        for (let j = 0; j < 24; j++) {
          this.heatmapData.push([j, i, Math.floor(Math.random() * 10)])
        }
      }

      this.rankingData = [
        { name: '101', value: 65 },
        { name: '102', value: 59 },
        { name: '103', value: 80 },
        { name: '201', value: 81 },
        { name: '202', value: 56 }
      ]
    },
    initCharts() {
      this.realTimeChart = echarts.init(document.getElementById('realTimeChart'))
      this.regionPie = echarts.init(document.getElementById('regionPie'))
      this.heatmapChart = echarts.init(document.getElementById('heatmapChart'))
      this.rankingChart = echarts.init(document.getElementById('rankingChart'))
      this.updateCharts()
    },
    updateCharts() {
      this.updateRealTimeChart()
      this.updateRegionPie()
      this.updateHeatmap()
      this.updateRankingChart()
    },
    updateRealTimeChart() {
      this.realTimeChart.setOption({
        tooltip: {
          trigger: 'axis',
          formatter: params => {
            return `时间: ${params[0].name}<br/>当前: ${params[0].value} kW<br/>昨日: ${params[0].data.diff} kW`
          }
        },
        grid: {
          top: '15%',
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: this.realTimeData.map(item => item.time),
          axisLine: { lineStyle: { color: '#eee' } }
        },
        yAxis: {
          type: 'value',
          name: '功率(kW)',
          axisLine: { show: false },
          splitLine: { lineStyle: { color: '#f5f5f5' } }
        },
        series: [
          {
            name: '当前用电',
            type: 'line',
            smooth: true,
            data: this.realTimeData.map(item => ({
              value: item.current,
              diff: item.yesterday
            })),
            lineStyle: { width: 3 },
            itemStyle: { color: '#36a3f7' },
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: 'rgba(54, 163, 247, 0.5)' },
                { offset: 1, color: 'rgba(54, 163, 247, 0.1)' }
              ])
            }
          },
          {
            name: '昨日同期',
            type: 'line',
            smooth: true,
            data: this.realTimeData.map(item => item.yesterday),
            lineStyle: { width: 1, type: 'dashed' },
            itemStyle: { color: '#9e9e9e' }
          }
        ]
      })
    },
    updateRegionPie() {
      this.regionPie.setOption({
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          right: 10,
          top: 'center',
          data: this.regionData.map(item => item.name)
        },
        series: [
          {
            name: '用电分布',
            type: 'pie',
            radius: ['50%', '70%'],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 10,
              borderColor: '#fff',
              borderWidth: 2
            },
            label: { show: false },
            emphasis: {
              label: { show: true }
            },
            data: this.regionData
          }
        ]
      })
    },
    updateHeatmap() {
      this.heatmapChart.setOption({
        tooltip: {
          position: 'top',
          formatter: params => {
            return `时间: ${params.data[0]}时<br/>用电强度: ${params.data[1]}`
          }
        },
        grid: {
          top: '15%',
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: Array.from({length:24}, (_,i)=> `${i}时`),
          splitArea: { show: true }
        },
        yAxis: {
          type: 'category',
          data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
          splitArea: { show: true }
        },
        visualMap: {
          min: 0,
          max: 10,
          calculable: true,
          orient: 'horizontal',
          left: 'center',
          bottom: '0%',
          inRange: {
            color: ['#e0f3f8', '#abd9e9', '#74add1', '#4575b4', '#313695']
          }
        },
        series: [{
          name: '用电强度',
          type: 'heatmap',
          data: this.heatmapData,
          label: { show: false },
          emphasis: {
            itemStyle: { shadowBlur: 10, shadowColor: 'rgba(0, 0, 0, 0.5)' }
          }
        }]
      })
    },
    updateRankingChart() {
      this.rankingChart.setOption({
        tooltip: {
          trigger: 'axis',
          axisPointer: { type: 'shadow' }
        },
        grid: {
          top: '15%',
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'value',
          name: '能耗效率',
          axisLine: { lineStyle: { color: '#eee' } },
          splitLine: { lineStyle: { color: '#f5f5f5' } }
        },
        yAxis: {
          type: 'category',
          data: this.rankingData.map(item => item.name),
          axisLine: { show: false }
        },
        series: [
          {
            name: '评分',
            type: 'bar',
            data: this.rankingData.map(item => item.value),
            itemStyle: {
              color: params => {
                const colorList = ['#c23531','#2f4554','#61a0a8','#d48265','#91c7ae','#749f83','#ca8622']
                return colorList[params.dataIndex % colorList.length]
              },
              borderRadius: [0, 4, 4, 0]
            },
            label: {
              show: true,
              position: 'right',
              formatter: '{c}'
            }
          }
        ]
      })
    },
    cutoffPower(device) {
      this.$confirm(`确认要切断 ${device.location}-${device.name} 的电源吗？`, '警告', {
        confirmButtonText: '强制断电',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$message.success(`已切断 ${device.location}-${device.name} 的电源`)
      })
    },
    handleAction(action) {
      this.$message.info(`执行操作: ${action.name}`)
    },
    logout() {
      this.$confirm('确认要退出系统吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$router.push('/login')
      })
    }
  }
}
</script>

<style scoped lang="scss">
.dashboard-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f5f7fa;
  overflow: hidden;
}

.top-nav {
  flex-shrink: 0;
  height: 60px;
  padding: 0 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: white;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);

  .nav-buttons {
    display: flex;
    gap: 10px;

    .nav-btn {
      padding: 10px 15px;
      border-radius: 4px;
      transition: all 0.3s;

      i {
        margin-right: 5px;
      }

      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
      }
    }
  }

  .user-info {
    display: flex;
    align-items: center;
    gap: 15px;

    .welcome {
      font-size: 14px;
      color: #606266;
    }

    .el-tag {
      font-weight: bold;
    }
  }
}

.main-content {
  flex: 1;
  display: flex;
  padding: 20px;
  overflow: hidden;
  gap: 20px;

  .left-panel {
    width: 40%;
    display: flex;
    flex-direction: column;
    gap: 20px;
  }

  .right-panel {
    width: 60%;
    display: flex;
    flex-direction: column;
    gap: 20px;
  }
}

.chart-card {
  flex: 1;
  border-radius: 8px;
  overflow: hidden;

  .chart-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;

    h3 {
      font-size: 16px;
      color: #303133;
      display: flex;
      align-items: center;

      i {
        margin-right: 8px;
        color: #409EFF;
      }
    }
  }

  .chart-container {
    height: 300px;
    width: 100%;
  }
}

.alert-card {
  height: 40%;
  border-radius: 8px;

  .alert-header {
    display: flex;
    align-items: center;
    margin-bottom: 15px;

    h4 {
      font-size: 15px;
      color: #303133;
      display: flex;
      align-items: center;

      i {
        margin-right: 8px;
        color: #E6A23C;
      }
    }

    .badge {
      margin-left: 10px;
      background: #F56C6C;
      color: white;
      border-radius: 10px;
      padding: 2px 8px;
      font-size: 12px;
    }
  }

  .device-list {
    height: calc(100% - 50px);
    overflow-y: auto;

    .device-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 12px 15px;
      margin-bottom: 8px;
      background: #f8f9fa;
      border-radius: 4px;
      transition: all 0.3s;

      &.warn {
        background: #fef0f0;
        border-left: 3px solid #F56C6C;
      }

      .device-info {
        flex: 1;

        .location {
          font-weight: bold;
          color: #303133;
          margin-right: 10px;
        }

        .name {
          color: #606266;
          margin-right: 10px;
        }
      }

      &:hover {
        transform: translateX(5px);
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
      }
    }
  }
}

.standby-container {
  height: 100%;
  display: flex;
  flex-direction: column;

  h4 {
    font-size: 15px;
    color: #303133;
    display: flex;
    align-items: center;
    margin-bottom: 15px;

    i {
      margin-right: 8px;
      color: #E6A23C;
    }
  }

  .standby-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 15px;
    height: 100%;

    .device {
      display: flex;
      align-items: center;

      .location {
        font-weight: bold;
        color: #303133;
        margin-right: 10px;
      }

      .name {
        color: #606266;
      }
    }
  }

  .total-consumption {
    margin-top: 15px;
    padding: 10px;
    background: #f8f9fa;
    border-radius: 4px;
    text-align: center;

    .value {
      font-weight: bold;
      color: #F56C6C;
      margin-left: 5px;
    }
  }
}

.behavior-container {
  height: 60%;
  display: flex;
  gap: 20px;

  .heatmap-card, .ranking-card {
    flex: 1;
    border-radius: 8px;

    h4 {
      font-size: 15px;
      color: #303133;
      display: flex;
      align-items: center;
      margin-bottom: 15px;

      i {
        margin-right: 8px;
      }
    }

    .chart {
      height: calc(100% - 40px);
      width: 100%;
    }
  }

  .heatmap-card h4 i {
    color: #409EFF;
  }

  .ranking-card h4 i {
    color: #67C23A;
  }
}

/* 响应式调整 */
@media (max-width: 1200px) {
  .main-content {
    flex-direction: column;

    .left-panel, .right-panel {
      width: 100%;
    }
  }

  .behavior-container {
    flex-direction: column;
  }
}
</style>
